(function (globle) {
  "use strict";

  const $meetups = document.querySelector("#meetups");
  const $modalContainer = document.querySelector("#modal-container");
  const $form = document.forms["meetup-form"];

  const meetups = [
    {
      id: "m1",
      title: "Coding Bootcamp",
      subtitle: "Learn to code in 2 hours",
      description:
        "In this meetup, we will have some experts that teach you how to code!",
      imageUrl: "some",
      address: "Taiji Compus",
      contactEmail: "code@test.com",
      isFavorite: false,
    },
    {
      id: "m2",
      title: "Swim Together",
      subtitle: "Let's go for some swimming",
      description: "We will simply swim some rounds!",
      imageUrl: "",
      address: "Olympic",
      contactEmail: "swim@test.com",
      isFavorite: true,
    },
  ];

  function createMeetup(data) {
    const item = document.querySelector("#templates > article").cloneNode(true);

    let html = item.innerHTML;
    const reg = /{(.*?)}/g;
    const res = html.match(reg);
    res &&
      res.forEach(function (field) {
        const key = field.replace("{", "").replace("}", "");
        let value = data[key];
        if (key === "favoriteClass") {
          value = data.isFavorite ? "success" : "";
        } else if (key === "favoriteText") {
          value = data.isFavorite ? "Unfavorite" : "Favorite";
        }
        html = html.replaceAll(field, value);
      });
    item.innerHTML = html;

    if (data.isFavorite) {
      const h1 = item.querySelector("h1");
      h1.innerHTML = h1.innerHTML + ' <span class="badge">Favorite</span>';
    }

    $meetups.appendChild(item);
  }

  meetups.forEach(createMeetup);

  document.querySelector("#newMeetup").addEventListener("click", function () {
    $modalContainer.classList.remove("hide");
  });

  document.querySelector("#submitForm").addEventListener("click", function () {
    const newMeetup = {
      id: Math.random().toString(),
      title: $form.title.value,
      subtitle: $form.subtitle.value,
      description: $form.description.value,
      imageUrl: $form.imageUrl.value,
      contactEmail: $form.email.value,
      address: $form.address.value,
    };

    meetups.push(newMeetup);

    // add to list
    createMeetup(newMeetup);

    // close dialog
    cancelEdit();
  });

  document.querySelector("#cancel").addEventListener("click", cancelEdit);

  document
    .querySelector(".modal-backdrop")
    .addEventListener("click", cancelEdit);

  function cancelEdit() {
    $modalContainer.classList.add("hide");
    $form.reset();
  }

  function toggleFavorite(id) {
    const updatedMeetup = meetups.find((m) => m.id === id);
    updatedMeetup.isFavorite = !updatedMeetup.isFavorite;
  }
})(window);
